<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: guestbook.php 4 2008-08-03 01:43:03Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * 'registry_guestbook' class for the Fusion Registry.
 *
 * @package Fusion Registry
 * @version $Id: guestbook.php 4 2008-08-03 01:43:03Z registry.fusion $
 */

/**
 * Fusion Registry core require
 */
require_once(REGISTRY_PATH.'/lib/core.php');

/**
 * Class 'guestbook' is in charge of viewing, adding, and deleting guestbook entries.
 *
 * This class should be invoked by the parent integration harness.
 * Most functions of this class do not have return values, instead the
 * redirect function is called to print a pretty thank you message to the
 * end user and stops the procedural code.
 *
 * @package Fusion Registry
 */
class registry_guestbook
{
    var $ipsclass;

    /**#@+ @var string */
    var $output     = "";
    var $page_title = "";
    /**#@-*/

    /**#@+ @var array */
    var $data            = array();
    var $registry_config = array();
    var $nav_bar         = array();
    var $html            = array( 'core', 'guestbook' );
    var $lib             = array( 'custom_fields', 'functions', 'parser' );
    /**#@-*/

    /** @var object Fusion Registry core */
    var $core = "";

    /**
     * Invoked from parent harness, this executes the code.
     *
     * This is the only function which should be called from the harness.
     * This function is the traffic cop for this class, it should
     * do very little procedural code, if any.
     *
     * @param string $param Function to call
     */
    function auto_run($param='')
    {
        // Initialize core
        $this->core = new registry_core();
        $this->core->ipsclass =& $this->ipsclass;
        $this->core->auto_run(&$this);

        // Setup parser
        $this->lib['parser']->parse_smilies = $this->registry_config['allow_bbcode_gb'];
        $this->lib['parser']->parse_bbcode  = $this->registry_config['allow_bbcode_gb'];
        $this->lib['parser']->parse_html    = $this->registry_config['allow_html_gb'];
        $this->lib['parser']->parse_nl2br   = 1;

        // Start our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."'>".$this->ipsclass->lang['title']."</a>";

        // Which way to go?
        switch( $param )
        {
            case 'do_add_comment':
                $this->data['body'] = $this->do_add_comment();
                break;

            case 'do_delete_comment':
                $this->data['body'] = $this->do_delete_comment();
                break;

            case 'view':
            default:
                $this->data['body'] = $this->view();
                break;
        }

        // Let's create the common output elements now
        $this->data['navigation']     = $this->lib['functions']->do_navigation();
        $this->data['latest_updated'] = $this->lib['functions']->do_latest_updated();
        $this->data['my_cars']        = $this->lib['functions']->do_my_items();

        // Print it all out
        $this->output = $this->core->process_output();

        $this->ipsclass->print->add_output( $this->output );

        // Shall we use our Custom page title, or the default one?
        $this->page_title = empty($this->page_title) ? $this->ipsclass->lang['page_title'] : $this->page_title;

        // Set the title and nav bar, print the output
        $this->ipsclass->print->do_output( array( 'TITLE' => $this->ipsclass->vars['board_name'] .' -> '. $this->page_title,
                                                  'NAV'   => $this->nav_bar ) );
    }


    /**
     * Signing the Guestbook of an item
     */
    function do_add_comment()
    {
        // Do they have permission?
        if ( ( $this->ipsclass->check_perms($this->registry_config['interact_perms']) != TRUE ) OR
             ($this->registry_config['enable_guestbooks'] != 1) )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // Flood check
        $this->ipsclass->DB->query("SELECT MAX(gb.post_date) as last_post FROM ibf_registry_guestbooks AS gb WHERE gb.author_id = '". $this->ipsclass->member['id'] ."'");
        $row = $this->ipsclass->DB->fetch_row();

        if ( $this->ipsclass->vars['flood_control'] > 0 )
        {
            if ($this->ipsclass->member['g_avoid_flood'] != 1)
            {
                if ( time() - $row['last_post'] < $this->ipsclass->vars['flood_control'] )
                {
                    $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'flood_control' , 'EXTRA' => $this->ipsclass->vars['flood_control'] ) );
                }
            }
        }

        // Will be used to store the created and updated time in DB.
        // We are not using mysql's timestamp format because we are
        // control freaks :)
        $epoch_time = time();

        // This constructs the FIELD_NAMES and FIELD_VALUES for sql
        $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'author_id'  => $this->ipsclass->member['id'],
                                                                           'ip_address' => $this->ipsclass->input['IP_ADDRESS'],
                                                                           'item_id'    => $this->ipsclass->input['CID'],
                                                                           'post'       => $this->lib['parser']->pre_db_parse( $this->ipsclass->input['post'] ),
                                                                           'post_date'  => $epoch_time,
                                                                  )      );

        // Execute the sql call
        $this->ipsclass->DB->query("INSERT INTO ibf_registry_guestbooks (" .$db_string['FIELD_NAMES']. ") VALUES (". $db_string['FIELD_VALUES'] .")");
        unset($db_string);

        // Should we send notification PM?
        $this->ipsclass->DB->query("SELECT m.members_display_name, g.guestbook_pm_notify
                                    FROM ibf_registry_items AS g
                                        LEFT JOIN ibf_members AS m ON g.member_id = m.id
                                    WHERE g.id='".$this->ipsclass->input['CID']."'");

        $row = $this->ipsclass->DB->fetch_row();

        // Only send if notify is turned on and we aren't signing our own item ;)
        if ( ($row['guestbook_pm_notify'] == 1) AND ($row['members_display_name'] != $this->ipsclass->member['members_display_name']) )
        {
            // Parse in our specifics
            $subject = preg_replace( "/<#FROM_MEMBER#>/", $this->ipsclass->member['members_display_name'], $this->ipsclass->lang['pm_notify_subject'] );
            $text    = preg_replace( "/<#FROM_MEMBER#>/", $this->ipsclass->member['members_display_name'], $this->ipsclass->lang['pm_notify_text'] );
            $text    = preg_replace( "/<#GUESTBOOK_LINK#>/", "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=view_guestbook&amp;CID=".$this->ipsclass->input['CID'], $text );

            // Send message
            $this->lib['functions']->send_msg( array( 'to'      => $row['members_display_name'],
                                                      'subject' => $subject,
                                                      'post'    => $text,
                                             )      );
        }

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['new_comment_success'], "autocom=".REGISTRY_URL."&amp;cmd=view_item&amp;CID={$this->ipsclass->input['CID']}" );
    }


    /**
     * Delete a guestbook comment, not undo-able
     */
    function do_delete_comment()
    {
        // Currently only Admin's can delete these, so we will make sure
        //   they are an Admin first!
        if ($this->ipsclass->member['g_is_supmod'] != 1)
        {
            // Get them outta here!!!
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        $this->ipsclass->DB->query( "DELETE FROM ibf_registry_guestbooks WHERE id='" . $this->ipsclass->input['id'] . "'" );

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['delete_comment_success'], "autocom=".REGISTRY_URL."&amp;cmd=view_guestbook&amp;CID={$this->ipsclass->input['CID']}" );
    }


    /**
     * Build the HTML for the Guestbook
     *
     * @return string Success returns template 'view_guestbook'; Failure returns template 'message'
     */
    function view()
    {
        $guestbook = array();

        // Do they have permission to browse?
        if ( ( $this->ipsclass->check_perms($this->registry_config['browse_perms']) != TRUE ) OR
             ($this->registry_config['enable_guestbooks'] != 1) )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        // First let's grab the user's item info
        $rs = $this->ipsclass->DB->query("SELECT m.members_display_name
                                          FROM ibf_members AS m
                                            LEFT JOIN ibf_registry_items AS g ON g.member_id = m.id
                                          WHERE g.id = '". $this->ipsclass->input['CID'] ."'");

        $member_info = $this->ipsclass->DB->fetch_row($rs);

        // First let's grab the user's item info
        $cf_entries = $this->lib['custom_fields']->get_cf_entries( array( 'WHERE' => "item_id='".$this->ipsclass->input['CID']."'" ) );

        // Setup our highlight for the title
        $cf_highlight = $this->lib['custom_fields']->get_cf_highlight();

        $guestbook['highlight_field_value'] = '';

        foreach ( $cf_highlight as $cf_field_id => $cf_highlight_row )
        {
            $guestbook['highlight_field_value'] .= $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_highlight_row,
                                                                                                         'value' => $cf_entries[$cf_field_id]['field_value'],
                                                                                                         'type' => 'view',
                                                                                                )      );
            // Append space for readability
            $guestbook['highlight_field_value'] .= ' ';
        }

        // Let's compile their guestbook summary
        $guestbook_id = $this->ipsclass->DB->query("SELECT gb.id, gb.post, gb.author_id, gb.post_date,
                                                        gb.ip_address, m.members_display_name, m.mgroup
                                                    FROM ibf_registry_guestbooks AS gb
                                                        LEFT JOIN ibf_members AS m ON gb.author_id = m.id
                                                    WHERE gb.item_id = '". $this->ipsclass->input['CID'] ."'
                                                    ORDER BY gb.post_date ASC");

        // If we don't have anything good to say..
        if ( ($total_msgs = $this->ipsclass->DB->get_num_rows() ) < 1 )
        {
            $guestbook['messages'] = $this->ipsclass->compiled_templates['skin_registry_guestbook']->empty_message();
        }
        else
        {
            $guestbook_msg = array();
            while ( $guestbook_msg = $this->ipsclass->DB->fetch_row($guestbook_id) )
            {
                // Make date human readable
                $guestbook_msg['post_date'] = $this->ipsclass->get_date( $guestbook_msg['post_date'], 'LONG' );

                // Parse the post 'safely'
                $guestbook_msg['post'] = $this->lib['parser']->pre_display_parse( $guestbook_msg['post'] );

                // Only show IP if Admin
                if ($this->ipsclass->member['g_is_supmod'] == 1)
                {
                    // Don't show admin IP
                    $guestbook_msg['ip_address'] = $guestbook_msg['mgroup'] == $this->ipsclass->vars['admin_group']
                                                 ? "<i>Private</i>"
                                                 : "[ <a href='{$this->ipsclass->base_url}act=usercp&amp;CODE=iptool&amp;ip={$guestbook_msg['ip_address']}' target='_blank'>{$guestbook_msg['ip_address']}</a> ]";

                    // Construct the IP HTML
                    $guestbook_msg['ip_address'] = $this->ipsclass->compiled_templates['skin_registry_guestbook']->ip_show($guestbook_msg['ip_address']);
                }
                else
                {
                    // No Admin = No IP shown!
                    $guestbook_msg['ip_address'] = '';
                }

                // Only show delete button if Admin
                $guestbook_msg['delete_button'] = '';

                if ($this->ipsclass->member['g_is_supmod'])
                {
                    $guestbook_msg['delete_button'] = "<a href=\"javascript:delete_post('{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=delete_comment&amp;id={$guestbook_msg['id']}&amp;CID={$this->ipsclass->input['CID']}')\"><{P_DELETE}></a>";
                }

                // Add this message to the list
                $guestbook['messages'] .= $this->ipsclass->compiled_templates['skin_registry_guestbook']->entry($guestbook_msg);
            }
        }

        // Finish off the end of the message list
        if ($total_msgs < 1)
        {
            $guestbook['messages'] .= '<div class="activeuserstrip">&nbsp;</div>';
        }

        // If they have permission to interact let's prep the add comments HTML
        if ( $this->ipsclass->check_perms($this->registry_config['interact_perms']) == TRUE )
        {
            $guestbook['add_comment'] = $this->ipsclass->compiled_templates['skin_registry_guestbook']->add_comment( array( CID => $this->ipsclass->input['CID'] ) );
        }

        // Pass along values to the guestbook template
        $guestbook['CID'] = $this->ipsclass->input['CID'];
        $guestbook['members_display_name'] = $member_info['members_display_name'];

        // Set page title
        $this->page_title = $member_info['members_display_name'] ."'s ". $guestbook['highlight_field_value'] .' '. $this->ipsclass->lang['guestbook'];

        // Add to our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=view_item&amp;CID={$this->ipsclass->input['CID']}'>{$guestbook['highlight_field_value']}</a>";

        return $this->ipsclass->compiled_templates['skin_registry_guestbook']->view($guestbook);
    }
}